package com.airena.controller;

import com.airena.aiservice.ConsultantService;
import com.airena.context.BaseContext;
import com.airena.entity.dto.MessageListDTO;
import com.airena.repository.RedisChatMemoryStore;
import com.airena.service.IRoleInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;


/**
 * ai聊天接口
 */
@RestController
@Slf4j
@Tag(name = "ai聊天接口")
public class ChatController {
    @Autowired
    private ConsultantService consultantService;

    @Autowired
    private IRoleInfoService roleInfoService;

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private RedisChatMemoryStore redisChatMemoryStore;

    /**
     * 跳转到聊天界面
     *
     * @return 聊天界面视图
     */
    @GetMapping("/chat-ui")
    public String chatUI() {
        return "index";
    }

    /**
     * 聊天接口
     *
     * @param memoryId 对话id
     * @param message  用户输入信息
     * @param roleId   选择的角色id
     * @return
     */
    @GetMapping(value = "/chat", produces = "text/html;charset=utf-8")
    @Operation(summary = "聊天接口")
    public Flux<String> chat(String memoryId, String message, Long roleId) {
        log.info("收到聊天请求: memoryId={}, message={}, roleId={}", memoryId, message, roleId);

        Long currentUserId = BaseContext.getCurrentId();
        BaseContext.setCurrentRoleId(roleId);
        
        // 将用户ID和角色ID存储到RedisChatMemoryStore实例中
        redisChatMemoryStore.setCurrentUserInfo(currentUserId, roleId);

        ListOperations listOperations = redisTemplate.opsForList();
        MessageListDTO messageListDTO = new MessageListDTO();
        messageListDTO.setMemoryId(memoryId);
        messageListDTO.setRoleId(roleId);

//        记录会话列表
        listOperations.leftPush(currentUserId, messageListDTO);
        try {
            // 拼接角色提示词
            String roleMessage = roleInfoService.getRoleInfoString(roleId);
            log.info("获取角色信息成功: {}", roleMessage);
            Flux<String> result = consultantService.chat(memoryId, message, roleMessage);
            return result;
        } catch (Exception e) {
            log.error("聊天处理过程中发生错误: ", e.getMessage(), e);
            // 返回错误信息
            return Flux.just("抱歉，处理您的请求时发生了错误: " + e.getMessage());
        }
    }
}